<template>
  <div class="batchDatIndex">
      <userHeader />
      <fixed />
    <div class="batchBannerIndex">
      <div class="breadClum">
        <span>
            <router-link :to="{path:'/pageIndex'}" >  <a class="bread1">当前位置：首页  >  </a></router-link>
            <router-link :to="{path:'/catalog'}" >   <a class="bread2">流程目录 ></a></router-link>
            <a class="bread2">批量定义基础数据</a>
        </span>
      </div>
      <div class="batchBanner">
           <span>文件上传格式说明，注意事项等;待后期编辑完善</span>
          <p class="downLoadTemp">
            <a href="http://neikong.ttfj.com/static/excel/批量添加流程模板.xlsx" download="template">下载模板</a>
          </p>
      </div>
      <el-form :model="model" enctype="multipart/form-data" >
        <el-form-item label="控制元素" :label-width="formLabelWidth" prop="element_id">
          <el-select v-model="model.element_id" placeholder="请选择控制元素" @change="selectEle">
            <el-option v-for="(item,index) in elementData" :key="index" :label=item.element_name :value=item.element_id></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级流程" :label-width="formLabelWidth" prop="process_pid"  >
          <el-tree
            :data="data3"
            :props="defaultProps"
            :show-checkbox="true"
            default-expand-all
            :check-on-click-node="true"
            node-key="process_id"
            ref="tree"
            @check-change="setCheckedKeys"
            @node-click="nodeClick"
            :expand-on-click-node="false"
            :check-strictly=true
            highlight-current
            >
          </el-tree>
        </el-form-item>
        <el-form-item label="上传批量excell文件" :label-width="formLabelWidth">
          <el-upload
            class='image-uploader'
            :multiple='false'
            :auto-upload='true'
            list-type='text'
            :show-file-list='true'
            :before-upload="beforeUpload"
            :drag='true'
            :limit="1"
            :data="upLoadData"
            action="/api/v1/flow/processbatch"
            :headers="headers"
            :on-exceed="handleExceed"
            :onSuccess="uploadSuccess"
            ref="upload"
             >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">一次只能上传一个文件，仅限excel格式，单文件不超过1MB</div>
          </el-upload>
          <!--<upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload"/>-->
          <!--<el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">-->
            <!--<el-table-column v-for="item of tableHeader" :prop="item" :label="item" :key="item"/>-->
          <!--</el-table>-->
          <!--<UploadExcelComponent :on-success="handleSuccess" :before-upload="beforeUpload">-->
          <!--</UploadExcelComponent>-->
        </el-form-item>
        <el-form-item>
          <div class="e-submit-btn">
            <el-button type="primary" @click="onSubmit" class="e-confirm-btn">确认</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>
<script>
  import fixed from '@/components/fixed.vue';
  import userHeader from '@/components/header.vue';
  import {strToHexCharCode,toFixedBit,dec2hex,formatTime,getNewDate } from  '@/utils/index.js'
  var mdSecret ='fangyou968123456'
//  import UploadExcelComponent from '@/page/excel/index.vue';
//  import XLSX from 'xlsx'
  export default({
    name: 'UploadExcel',
      data(){
          return {
            formLabelWidth:'230px',
            upLoadData:{},
            model:{},
            headers:{},
            file:'',
            fileList3: [{
              name: 'food.jpeg',
              url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
            }, {
              name: 'food2.jpeg',
              url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
            }],
            processTitle:'',
            process_id:'',
            tableData: [],
            tableHeader: [],
            elementData:[],
            data3: [ ],
            responseText:'',
            responseCode:'',
            defaultProps: {
              children: 'son_process',
              label: 'process_name'
            },
          }
      },
      components:{
        fixed,
        userHeader,
      },
      methods:{
        //树状结构流程目录读取
        getCatalogData(){
          this.axios.get('/api/v1/flow/processflat')
            .then((res)=>{
              if(res.data.code==0){
                console.log(res.data.data)
                this.data3 =res.data.data
              }else{
                this.$alert(res.data.message,'提示')
              }
            })
            .catch((err)=>{
              this.$alert(err.message,'提示')
            })
        },
        selectEle(val){
          console.log(val)
          this.choiseCate(val);
          this.upLoadData.element_id =val;
        },
        choiseCate(id){
          console.log(id);
          this.axios.get('/api/v1/flow/processflat/'+`${id}`)
            .then((res)=>{
              if(res.data.code==0){
                this.data3 =res.data.data;
              }
            })

        },
        //获取控制元素列表
        getElementData(){
          this.axios.get('/api/v1/flow/element')
            .then((res)=>{
              if(res.data.code==0){
                this.elementData =res.data.data
                console.log(this.elementData)
              }else{
                this.$alert(res.data.message,'提示')
              }
            }).catch((err)=>{
            this.$alert(err.message,'提示')
          })
        },
        uploadSuccess (response, file, fileList) {
            if(response.code==0){
              this.$alert(response.message,"提示")
            };
             console.log('上传文件', response);
            this.responseCode =response.code;
            this.responseText =response.message;
        },
        setCheckedKeys(data,checked,node){
          console.log(data)
          if(checked == true){
            this.checkedId = data.process_id;
            this.upLoadData.process_pid =this.checkedId||0;
            this.$refs.tree.setCheckedNodes([data]);
          }
        },
        nodeClick(data){
          this.checkedId = data.process_id;
          this.upLoadData.process_pid =this.checkedId||0;
          console.log( this.upLoadData.process_pid)
          this.$refs.tree.setCheckedNodes([data]);
        },
      // 上传文件之前的钩子
    beforeUpload (file) {
      if(!this.upLoadData.element_id){
          this.$alert('请选择控制元素',"提示")
          return false;
      };
      this.upLoadData.process_pid =this.checkedId||0;
      this.upLoadData.excel =file;
      console.log(file.size/1024/1024);
      if(file.size/1024/1024>2){
          this.$alert('上传文件不超过2M','提示');
          return false;
      }
      const isText = file.type === 'application/vnd.ms-excel'
      const isTextComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      return (isText | isTextComputer)
    },
    // 上传文件个数超过定义的数量
    handleExceed (files, fileList) {
      this.$alert('当前限制选择 1 个文件，请删除后继续上传','提示')
    },
    beforeunloadHandler(){
    },
    // 上传文件
    uploadFile (item) {
      console.log(item);
      const fileObj = item.file;
      // FormData 对象
      const form = new FormData();
      console.log(fileObj);
      // 文件对象
      form.append('file', fileObj)
      console.log(form.get(fileObj))
      console.log(JSON.stringify(form))

//      this.axios.post('/api/v1/flow/processbatch',
//        {
//          process_pid:this.process_id,
//          excel:fileObj
//        },
//        {
//          headers: {
//            token:toFixedBit(strToHexCharCode(`${mdSecret}${currentTime}`),52,true,0,true),
//            timeStamp:currentTime,
//            sign:this.MD5(`${localStorage.getItem('user_name')}${localStorage.getItem('token')}${currentTime}`)
//          }
//        })
//        .then((res)=>{
//          if(res.data.code==0){
//            console.log(res.data.data)
//            this.data3 =res.data.data
//          }else{
//            this.$alert(res.data.message,'提示')
//          }
//        })
//        .catch((err)=>{
//          this.$alert(err.message,'提示')
//        })
      // let formTwo = JSON.stringify(form)
//      EnterAPI.iExcel(form).then(response => {
//        console.log('MediaAPI.upload')
//        console.log(response)
//        this.$message.info('文件：' + fileObj.name + '上传成功')
//      })

    },
        handleSuccess({ results, header }) {
          console.log(results)
        },
      onSubmit(){
            if(this.responseCode==0){
              this.$alert('文件上传成功,点击即将返回上级页面','提示',{
                confirmButtonText: '确定',
                callback: action => {
                  this.$refs.upload.clearFiles();
                  this.$router.push({
                    path:'/catalog'
                  })
                }});
            }else{
              this.$alert(this.responseText,'提示');
            }

//        var currentTime =parseInt(getNewDate((formatTime(new Date()))).getTime()/1000);
//        this.axios.post('/api/v1/flow/processbatch',
//          {
//            process_pid:this.process_id,
//            excel:this.file
//          },
//          {
//            headers: {
//              token:toFixedBit(strToHexCharCode(`${mdSecret}${currentTime}`),52,true,0,true),
//              timeStamp:currentTime,
//              sign:this.MD5(`${localStorage.getItem('user_name')}${localStorage.getItem('token')}${currentTime}`)
//            }
//          })
//          .then((res)=>{
//            if(res.data.code==0){
//              console.log(res.data.data)
//            }else{
//              this.$alert(res.data.message,'提示')
//            }
//          })
//          .catch((err)=>{
//            this.$alert(err.message,'提示')
//          })
      }
    },
    mounted(){
          this.getElementData();
          var currentTime =parseInt(getNewDate((formatTime(new Date()))).getTime()/1000);
          this.headers = {
            token:toFixedBit(strToHexCharCode(`${mdSecret}${currentTime}`),52,true,0,true),
            timeStamp:currentTime,
            sign:this.MD5(`${sessionStorage.getItem('user_name')}${sessionStorage.getItem('token')}${currentTime}`)
          };
        window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))

    }
  })
</script>


<style scoped>
  .batchDatIndex{
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    padding: 10px;
    /*background-color: white;*/
    /*height: 100%;*/

  }
  .batchBannerIndex{
    background: white;
    height: calc( 100% - 70px);
  }
  .batchBanner{
    height: 112px;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    margin: 15px 30px 38px 30px;
    background: #e9f3db;
    text-align: left;
    color: #8cc34e;
    font-size:14px ;
    overflow: hidden;
  }
  .batchBanner span{
    display: block;
    padding-left:67px;
    position: relative;
    font-weight: bold;
    color: #5d9120;
    margin-top: 20px;
  }
  .batchBanner span:before{
    position: absolute;
    content: '';
    left: 42px;
    top:50%;
    width:22px ;
    height:22px ;
    background-image: url("../../static/images/info_green.png");
    background-repeat: no-repeat;
    background-position: center;
    margin-top: -11px;

  }
  .batchBanner .downLoadTemp{
    margin-top: 20px;
  }
  .batchBanner .downLoadTemp a{
    background: #8cc34b;
    border-color: #8cc34b;
    color: white;
    padding: 9px 22px;
    border-radius: 6px;
    -webkit-border-radius: 6px;
    -moz-border-radius: 6px;
    margin-left:67px;
  }
  .batchDatIndex .el-form >>> .el-form-item .el-form-item__content .e-confirm-btn{
    margin-left: 230px;
    padding: 9px 18px;
  }
  .batchDatIndex .el-form >>> .el-form-item .el-form-item__content .e-upload-file{
    background: #769dd6;
    border-color: #769dd6;
  }
  .batchDatIndex  >>> .el-form-item .el-form-item__content{
    text-align: center;
    width: 360px;
  }
  .batchDatIndex  >>> .el-form-item .el-form-item__content .el-select{
    width: 100%;
  }
  .batchDatIndex  >>> .el-form-item .el-tree__empty-block{
    line-height: 40px;
    height: 40px;
    min-height: 40px;
  }
  .batchDatIndex >>>   .el-form-item  .el-tree .el-tree-node{
    margin-top: 6px;
  }
  @media screen  and (max-width: 1400px) {
    .batchDatIndex{
      padding: 6px;
    }
  }
</style>
